# problems/views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status

from management.middleware import skip_middleware_user_activity
from utils.logging_utils import log_request_response
from .models import Problem
from .serializers import ProblemSerializer
from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404
from tag.models import Tag


# 分页获取所有题目
@api_view(['GET'])
@skip_middleware_user_activity
@log_request_response
def get_all_problems(request):
    problems = Problem.objects.all()

    # 筛选
    difficulty = request.GET.get('difficulty')
    if difficulty:
        problems = problems.filter(difficulty=difficulty)

    tag = request.GET.get('tag')
    if tag:
        problems = problems.filter(tags__tag_name=tag)

    # 分页
    page = request.GET.get('page', 1)
    page_size = request.GET.get('page_size', 10)
    paginator = Paginator(problems, page_size)
    current_page = paginator.page(page)

    serializer = ProblemSerializer(current_page, many=True)
    return Response({
        'page': int(page),
        'page_size': int(page_size),
        'total_pages': paginator.num_pages,
        'total_problems': paginator.count,
        'problems': serializer.data
    })


# 通过problem_number获取对应题目信息
@api_view(['GET'])
@skip_middleware_user_activity
@log_request_response
def get_problem_by_number(request, problem_number):
    try:
        problem = Problem.objects.get(problem_number=problem_number)
        serializer = ProblemSerializer(problem)
        return Response(serializer.data)
    except Problem.DoesNotExist:
        return Response({"error": "Problem not found."}, status=status.HTTP_404_NOT_FOUND)


# 通过标签名获取该标签下的所有题目
@api_view(['GET'])
@skip_middleware_user_activity
@log_request_response
def get_problems_by_tag(request, tag_name):
    # 获取标签对象，如果不存在则返回404
    tag = get_object_or_404(Tag, tag_name=tag_name)

    # 获取所有与该标签相关的题目
    problems = tag.problems.all()

    # 序列化问题数据
    serializer = ProblemSerializer(problems, many=True)

    # 返回序列化数据
    return Response(serializer.data)


# 通过标签下标获取该标签下所有的题目
@api_view(['GET'])
@skip_middleware_user_activity
@log_request_response
def get_problems_by_tag_index(request, tag_index):
    # 获取标签对象，如果不存在则返回404
    tag = get_object_or_404(Tag, index=tag_index)

    # 获取所有与该标签相关的题目
    problems = tag.problems.all()

    # 序列化问题数据
    serializer = ProblemSerializer(problems, many=True)

    # 返回序列化数据
    return Response(serializer.data)


from django.http import HttpResponse, Http404
from django.conf import settings
from .models import Problem
import os
from rest_framework.decorators import api_view


# 通过problem_number获取题面内容
@api_view(['GET'])
@skip_middleware_user_activity
@log_request_response
def get_problem_content(request, problem_number):
    try:
        # 检查问题编号是否存在于数据库中
        problem = Problem.objects.get(problem_number=problem_number)

        # 构建文件路径
        problem_type = problem_number[0]  # 'P' 或 'B'
        number_part = int(problem_number[1:])  # 从'P1000'取出1000
        folder_number = number_part // 1000
        # 将 file_path 拼接改为使用 'static' 文件夹路径
        file_path = os.path.join(settings.BASE_DIR, 'static',
                                 f'problem_content/{problem_type}/{folder_number}/{problem_number}.md')

        print(file_path)

        # 尝试打开和读取文件内容
        if os.path.exists(file_path):
            with open(file_path, 'r', encoding='utf-8') as file:
                content = file.read()
            return HttpResponse(content, content_type='text/markdown')
        else:
            return HttpResponse("Problem content file not found.", status=404)

    except Problem.DoesNotExist:
        # 如果问题编号不存在
        return HttpResponse("Problem number does not exist.", status=404)
    except Exception as e:
        # 处理可能发生的其他异常
        return HttpResponse(f"An error occurred: {str(e)}", status=500)
